﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SwParaPlatform2.dlgUIConfig;
using SwParaPlatform2.dlgRuleConfig;
using SwParaPlatform2.logger;


namespace SwParaPlatform2
{
    public partial class MainForm : Form
    {
        private List<PageBase> pages;
        private int currentPageIndex;
        public bool isProgrammaticallyClosed = false;
        public string sFilePath = null;

        public delegate void FormClosedEventHandler(object sender, bool ProgrammaticallyClosed, bool bNeedCloseCurrentControl);

        public event FormClosedEventHandler FormClosedEvent;

        public MainForm()
        {
            InitializeComponent();
            InitializePages();
            this.FormClosing += MainForm_FormClosing;
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // MainForm
            // 
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
            this.AutoSize = true;
            this.ClientSize = new System.Drawing.Size(744, 591);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.Name = "MainForm";
            this.Text = "参数配置";
            this.ResumeLayout(false);

        }

        private void InitializePages()
        {
            pages = new List<PageBase>
            {
                new dlgUIConfigView(),
                new dlgRuleConfigView(),
            };

            foreach (var page in pages)
            {
                page.NextClicked += (s, e) => ShowPage(currentPageIndex + 1);
                page.PrevClicked += (s, e) => ShowPage(currentPageIndex - 1);
                this.Controls.Add(page);
                page.Dock = DockStyle.Fill;
                page.Visible = false;
            }

            currentPageIndex = 0;
            ShowPage(currentPageIndex);
        }

        private void ShowPage(int pageIndex)
        {
            try
            {
                if (pageIndex < 0 || pageIndex >= pages.Count)
                    return;

                pages[currentPageIndex].Visible = false;
                currentPageIndex = pageIndex;
                pages[currentPageIndex].Visible = true;
                pages[currentPageIndex].DoShowPage();

                // 设置按钮的显示状态
                pages[currentPageIndex].SetButtonVisibility(currentPageIndex > 0, currentPageIndex < pages.Count - 1);
            }
            catch (Exception ex) 
            {
                Logger.Instance.Log($"Exception in ShowPage = {ex.Message}");
            }
            
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            foreach (var page in pages)
            {
                page.Cleanup();
                page.Dispose();
            }
            FormClosedEvent?.Invoke(sender, isProgrammaticallyClosed, true);
        }
    }

    public class DetailsForm : Form
    {
        private DataGridView dataGridView;
        private Button saveButton;
        private Dictionary<string, object> nodeData;
        private string nodeName;
        private string nodePath;

        public DetailsForm(Dictionary<string, object> nodeData, string nodeName, string nodePath)
        {
            this.nodeData = nodeData;
            this.nodeName = nodeName;
            this.nodePath = nodePath;

            InitializeComponent();
            LoadData(nodeData);
        }

        private void InitializeComponent()
        {
            this.Text = nodeName;
            this.Size = new System.Drawing.Size(400, 250);
            this.StartPosition = FormStartPosition.CenterParent;

            dataGridView = new DataGridView
            {
                Dock = DockStyle.Top,
                AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill,
                AllowUserToAddRows = false,
                AllowUserToDeleteRows = false,
                ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize
            };

            saveButton = new Button
            {
                Text = "保存",
                Dock = DockStyle.Bottom
            };
            saveButton.Click += SaveButton_Click;

            this.Controls.Add(dataGridView);
            this.Controls.Add(saveButton);
        }

        private void LoadData(Dictionary<string, object> nodeData)
        {
            dataGridView.Columns.Clear();
            dataGridView.Rows.Clear();

            dataGridView.Columns.Add("Key", "Key");
            dataGridView.Columns.Add("Value", "Value");

            foreach (var key in nodeData.Keys)
            {
                if (key == "SubComp") continue;

                var headerText = DataStore.Instance.HeaderMapping.ContainsKey(key) ? DataStore.Instance.HeaderMapping[key] : key;

                var row = new DataGridViewRow();
                row.CreateCells(dataGridView);
                row.Cells[0].Value = headerText;
                row.Cells[1].Value = nodeData[key] == null || nodeData[key].ToString() == "null" ? "" : nodeData[key].ToString();

                if (key != "Equation")
                {
                    row.Cells[1].ReadOnly = true;
                    row.Cells[1].Style.BackColor = System.Drawing.Color.LightGray;
                }

                dataGridView.Rows.Add(row);
            }
        }

        private void SaveButton_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                var key = DataStore.Instance.HeaderMapping.ContainsValue(row.Cells[0].Value.ToString())
                    ? DataStore.Instance.HeaderMapping.FirstOrDefault(x => x.Value == row.Cells[0].Value.ToString()).Key
                    : row.Cells[0].Value.ToString();

                if (nodeData.ContainsKey(key))
                {
                    nodeData[key] = row.Cells[1].Value.ToString();
                }
            }

            DataStore.Instance.UpdateTreeViewData(nodePath, nodeData);
            this.Close();
        }
    }
}

